package arrays;

import java.util.HashSet;
import java.util.Set;

/**
 * @author pengfei.hpf
 * @date 2020/3/4
 * @verdion 1.0.0
 */
public class TotalFruit {

    public int totalFruit(int[] tree) {
        if(tree == null || tree.length == 0){
            return 0;
        }
        int start = 0;
        int diff = 1;
        int count = 1;
        int max = 1;
        Set<Integer> set = new HashSet<>();
        set.add(tree[0]);
        for(int i = 1; i < tree.length; i ++){
            if(tree[i] != tree[i -1]){
                if(!set.contains(tree[i])){
                    diff ++;
                    set.add(tree[i]);
                }
                if(diff > 2){
                    diff = 1;
                    count = i - start + 1;
                    set.remove(tree[start - 1]);
                } else {
                    count ++;
                }
                start = i;
            } else {
                count ++;
            }
            max = Math.max(max, count);
        }
        return max;
    }

    public static void main(String[] args){
        System.out.println((new TotalFruit()).totalFruit(new int[]{3,3,3,1,2,1,1,2,3,3,4}));
    }
}
